package lumis.service.group;

import lumis.doui.processaction.ProcessActionHandler;
import lumis.doui.source.Source;
import lumis.portal.PortalException;
import lumis.portal.group.GroupConfig;
import lumis.portal.manager.ManagerFactory;
import lumis.service.group.DomainScopeFilter;
import lumis.util.XmlUtil;

/**
 * Persists the group information using the custom property domain value.
 *
 * @version $Revision: 10825 $ $Date: 2009-08-04 12:36:40 -0300 (Tue, 04 Aug 2009) $
 * @since 5.0.0
 */
public class GroupProcessActionHandler extends ProcessActionHandler<Source<?>>
{
	public static final String GROUP_ADD = "lum_groupAdd";
	
	public void processAction() throws PortalException
	{
		String actionType = XmlUtil.readAttributeString("actionType", processActionNode);

		if (actionType == null)
			actionType = GroupProcessActionHandler.GROUP_ADD;

		if (actionType.equals(GroupProcessActionHandler.GROUP_ADD))
			processAddAction();
		else
			throw new PortalException("Unknow action type");
	}
	
	private void processAddAction() throws PortalException
	{
		String alias = getParameter("alias", String.class); 
		String name = getParameter("name", String.class); 
		String description = getParameter("description", String.class); 
		
		// Gets the domain from service instance custom properties
		String serviceInstanceId = douiContext.getRequest().getServiceInstanceConfig().getId();
		String channelId = ManagerFactory.getServiceInstanceManager().getCustomProperty(sessionConfig, serviceInstanceId, 
			DomainScopeFilter.DOMAIN_CUSTOM_PROPERTY_NAME, transaction);
		
		// if the domain is global put null in channelId
		if(DomainScopeFilter.GLOBAL_DOMAIN_VALUE.equals(channelId))
			channelId = null;

		// create the group to be added
		GroupConfig group = new GroupConfig();
		group.setAlias(alias);
		group.setName(name);
		group.setDescription(description);
		group.setType(GroupConfig.GROUP_TYPE_STANDARD);
		group.setChannelId(channelId);

		if (channelId == null)
		{
			// set group type for global groups
			String groupTypeId = getParameter("groupTypeId", String.class);
			if (groupTypeId != null)
				group.setGroupTypeId(groupTypeId);
		}

		// add the group
		ManagerFactory.getGroupManager().add(sessionConfig, group, transaction);

		addDefaultResponse();
	}
}
